package chpt09;

import java.time.LocalDateTime;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

class TaskNoDealy implements Runnable{

	@Override
	public void run() {
		System.out.println("TaskNoDealy: "+LocalDateTime.now());
	}
	
}

class TaskWithDealy implements Runnable{
	private Random rnd;
	private int delay; //最长延迟时间为delay-1

	public TaskWithDealy(int delay) {
		this.delay = delay;
		this.rnd = new Random();
	}


	@Override
	public void run() {
		int sleepTime = rnd.nextInt(delay);
		System.out.print("TaskWithDealy: "+LocalDateTime.now());
		System.out.println(". 任务持续了" + sleepTime + "秒.");
		try {
			TimeUnit.SECONDS.sleep(sleepTime);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}

public class ScheduledExecutorTest {

	public static void main(String[] args) {
		

		Runnable scheduledTask = new TaskNoDealy();//new TaskWithDealy();

		ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
		//ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
		
		ScheduledFuture<?> scheduledFuture = scheduler.scheduleAtFixedRate(scheduledTask, 1000, 2000, TimeUnit.MILLISECONDS);
		//ScheduledFuture<?> scheduledFuture = executor.scheduleWithFixedDelay(scheduledTask, 1000, 2000,TimeUnit.MILLISECONDS);
		
		//10秒后尝试结束scheduler中的任务
		scheduler.schedule(new Runnable() {
			
			@Override
			public void run() {
				scheduledFuture.cancel(true); //取消未开始的任务
				scheduler.shutdown();
				System.out.println("任务结束");
				
			}
		}, 10, TimeUnit.SECONDS);
		System.out.println("main end");

	}

}
